<!-- eslint-disable vue/no-unused-vars -->
<template>
  <div id="roles">
    <!-- 面包屑区域 -->
    <div class="mianbaoxie">
      <el-breadcrumb separator-class="el-icon-arrow-right">
        <el-breadcrumb-item :to="{ path: '/' }">首页</el-breadcrumb-item>
        <el-breadcrumb-item>权限管理</el-breadcrumb-item>
        <el-breadcrumb-item>角色列表</el-breadcrumb-item>
      </el-breadcrumb>
    </div>
    <el-card>
      <el-row>
        <el-col>
          <el-button type="primary" style="margin-bottom: 20px">添加用户</el-button>
        </el-col>
        <el-col>
          <el-table :data="RolesList" border stripe>
            <el-table-column type="expand">
              <template slot-scope="scope">
                <el-row v-for="(item1, i1) in scope.row.children" :key="item1.id" :class="['bdbottom', il === 0 ? 'bdtop' : '']" class="duiqi" @close="remEltagId(scope.row, item3.id)">
                  <!-- 一级标题 -->
                  <el-col :span="5">
                    <el-tag>{{ item1.authName }}</el-tag>
                    <i class="el-icon-arrow-right"></i>
                  </el-col>
                  <!-- 二级内容 -->
                  <el-col :span="19">
                    <el-row v-for="(item2, i2) in item1.children" :key="item2.id" :class="[i2 === 0 ? '' : 'bdtop']" class="duiqi" @close="remEltagId(scope.row, item3.id)">
                      <el-col :span="6">
                        <el-tag>{{ item2.authName }}</el-tag>
                        <i class="el-icon-arrow-right"></i>
                      </el-col>
                      <!-- 三级内容 -->
                      <el-col :span="18" class="duiqi">
                        <el-tag type="warning" closable v-for="(item3, i3) in item2.children" :key="item3.id" @close="remEltagId(scope.row, item3.id)">{{ item3.authName }} </el-tag>
                      </el-col>
                    </el-row>
                  </el-col>
                </el-row>
              </template>
            </el-table-column>
            <el-table-column prop="index" label="#" width="100" type="index"> </el-table-column>
            <el-table-column prop="roleName" label="角色名称"> </el-table-column>
            <el-table-column prop="roleDesc" label="角色描述"> </el-table-column>
            <el-table-column prop="path" label="操作">
              <template slot-scope="scope">
                <el-button type="primary" icon="el-icon-edit">编辑</el-button>
                <el-button type="danger" icon="el-icon-delete">删除</el-button>
                <el-button type="warning" icon="el-icon-s-tools" @click="onshowSetRightDialog(scope.row)">分配权限</el-button>
              </template>
            </el-table-column>
          </el-table>
        </el-col>
      </el-row>
    </el-card>
    <!-- 这是 分配权限 的弹出框（对话框） -->
    <el-dialog title="分配权限" :visible.sync="showSetRightDialog" width="3 0%" @close="onchangeshowSetRightDialog">
      <!-- 树形控件 -->
      <el-tree :data="SetRightDialog" show-checkbox node-key="id" :default-checked-keys="defkeys" :props="defaultProps" default-expand-all ref="treeRef"> </el-tree>
      <span slot="footer" class="dialog-footer">
        <el-button @click="showSetRightDialog = false">取 消</el-button>
        <el-button type="primary" @click="allotRights">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
export default {
  name,
  data() {
    return {
      RolesList: [],
      // 这是 分配权限 的弹出框 的显示和隐藏状态
      showSetRightDialog: false,
      // 获取所有的分配权限
      SetRightDialog: [],
      defaultProps: {
        children: 'children',
        label: 'authName'
      },
      // 默认选中的节点中的id值数组
      defkeys: [],
      // 当前即将分配权限的角色id
      roleId: ''
    }
  },
  // 生命周期函数？
  created() {
    this.getRolesList()
  },
  methods: {
    // 展示分配权限 的  点击弹出对话框
    async onshowSetRightDialog(role) {
      this.roleId = role.id
      // 获取数据
      const { data: res } = await this.$http.get('rights/tree ')
      if (res.meta.status !== 200) {
        return this.$message.error('删除授权失败')
      }
      this.SetRightDialog = res.data
      // 通过递归获取三级下所有的id
      this.getdefkeys(role, this.defkeys)
      this.showSetRightDialog = true
    },
    async getRolesList() {
      const { data: res } = await this.$http.get('roles')
      this.RolesList = res.data
    },
    // 根据当前的id删除对应的内容
    async remEltagId(role, rightId) {
      const confimResult = await this.$confirm('此操作将永久删除该文件, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).catch((err) => err) // 当用户取消
      if (confimResult !== 'confirm') {
        return this.$message.info('你取消了删除')
      }
      this.$message.success('删除成功')
      // 但用户确认删除
      // 调取 删除 请求
      const { data: res } = await this.$http.delete(`roles/${role.id}/rights/${rightId}`)
      if (res.meta.status !== 200) {
        return this.$message.error('删除授权失败')
      }
      role.children = res.data
    },
    // 通过递归的形式,获取用户下所有三级权限的id,并且保存到 defkeys 数组里面
    getdefkeys(node, arr) {
      console.log(node, arr)
      // 如果当前node节点不包含 children 属性，则是三级节点
      if (!node.children) {
        return arr.push(node.id)
      }
      node.children.forEach((item) => this.getdefkeys(item, arr))
    },
    //  监听页面数据关闭事件
    onchangeshowSetRightDialog() {
      this.defkeys = []
    },
    // 点击为角色分配权限
    async allotRights() {
      // 把 选中和版选中的拼接起来
      // getCheckedKeys若节点可被选择（即 show-checkbox 为 true），则返回目前被选中的节点的 key 所组成的数组
      // getHalfCheckedKeys若节点可被选择（即 show-checkbox 为 true），则返回目前半选中的节点的 key 所组成的数组
      // keys:权限id
      const keys = [...this.$refs.treeRef.getCheckedKeys(), ...this.$refs.treeRef.getHalfCheckedKeys()]
      console.log(keys)
      // 拼接起来
      const idStr = keys.join(',')
      const { data: res } = await this.$http.post(`roles/${this.roleId}/rights`, { rids: idStr })
      console.log(res)
      if (res.meta.status !== 200) {
        return this.$message.error('分配权限失败')
      }
      this.$message.success('分配权限成功')
      this.getRolesList() // 数据更新
      this.showSetRightDialog = false // 隐藏对话框
    }
  }
}
</script>

<style>
.el-tag {
  margin: 10px;
}
.bdtop {
  border-top: 1px solid #eee;
}
.bdbottom {
  border-bottom: 1px solid #eee;
}
.duiqi {
  display: flex;
  align-items: center;
}
</style>
